package ca.etsmtl.log430.lab3;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.ArrayList;
import java.util.Collections;

public class SortFilter extends Thread {
	boolean done;
	ArrayList<Projet> list = new ArrayList<Projet>();
	PipedReader inputPipe = new PipedReader();
	PipedWriter outputPipe = new PipedWriter();

	public SortFilter(PipedWriter inputPipe,
			PipedWriter outputPipe) {

	
		try {

			// Connect inputPipe
			this.inputPipe.connect(inputPipe);

			// Connect outputPipe
			this.outputPipe = outputPipe;

		} catch (Exception Error) {

		} // try/catch

	} // Constructor
	
	public void run() {

		// Declarations

		char[] characterValue = new char[1];
		String[] champs = new String[7];
		// char array is required to turn char into a string
		String champ = "";
		int i = 0;
		// string is required to look for the keyword
		int integerCharacter; // the integer value read from the pipe

		try {

			done = false;

			while (!done) {

				integerCharacter = inputPipe.read();
				characterValue[0] = (char) integerCharacter;

				if (integerCharacter == -1) { // pipe is closed

					done = true;

				} else {

					if (integerCharacter == '\n') { // end of line
						
						champs[i] = champ;
						list.add(new Projet(champs[0],champs[1],champs[2],champs[3],champs[4],champs[5],champs[6]));
						i=0;
						champ = "";

					} 
					else if(integerCharacter == ' ' &&  i < 6)
					{
							champs[i] = champ;
							i++;
							champ = "";
					}
					else {

						champ += new String(characterValue);

					} // if //

				} // if

			} // while

		} catch (Exception error) {

		} // try/catch

		Collections.sort(list);
		
		for (int j = 0; j < list.size(); j++) {
			String lineOfText = list.get(j).toString();
			try {
				outputPipe.write(lineOfText, 0, lineOfText.length());
				outputPipe.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
		try {

			inputPipe.close();

			outputPipe.close();

		} catch (Exception error) {


		} // try/catch

	} // run
}
